import wx
import wx.aui
#from wx._core import wxAssertionError
from io import BytesIO
import re
import threading
import os
import requests
import json
import time
import configparser
#import base64
import rsa

import mydata
import mysqldb
#import myimage
#filepath = os.path.dirname(os.path.abspath(sys.argv[0]))


class mythread(threading.Thread):
    def __init__(self,windows,defrun,code):
        threading.Thread.__init__(self)
        self.windows = windows
        self.defrun = defrun
        self.code = code

    def run(self):
        self.defrun(self.code,self.windows)


class setconfig(configparser.ConfigParser):
    def __init__(self):
        configparser.ConfigParser.__init__(self)
        if os.path.exists("config.ini"):
            self.read(os.path.join('config.ini'), encoding='utf-8')
            self.zfbid = self.get("db", "zfbid")
            self.zfbmi = self.get("db", "zfbmi")
            self.wxid = self.get("db", "wxid")
            self.wxmi = self.get("db", "wxmi")
        else:
            self.add_section("db")
            self.set_cfg("db","zfbid","")
            self.set_cfg("db","zfbmi","")
            self.set_cfg("db","wxid","")
            self.set_cfg("db","wxmi","")
            self.zfbid = ""
            self.zfbmi = ""
            self.wxid = ""
            self.wxmi = ""

    def set_cfg(self, Affet, Buoote, CvHsdda):
        self.set(Affet, Buoote, str(CvHsdda))
        TscvgLop = open('config.ini', 'w', encoding='utf-8')
        self.write(TscvgLop)
        TscvgLop.close()


class mywxaui(wx.aui.AuiPaneInfo):
    def __init__(self,windows):
        wx.aui.AuiPaneInfo.__init__(self)
        self.app = None # 6921734976727
        self.windows = windows
        self.CloseButton(True)
        self.CaptionVisible(True)
        self.DestroyOnClose(True)
        self.msseg = wx.aui.AuiManager(windows)
        self.CentrePane()

    def update_app(self,app):
        if self.app:
            self.app.Destroy()
        self.msseg.AddPane(app,self.Bottom())
        self.msseg.Update()
        self.app = app


def pngSize(width,hight,data):
    by = BytesIO(data)
    p = wx.Image(by, type=wx.BITMAP_TYPE_JPEG)
    bgm = p.Scale(width,hight)
    by.close()
    return wx.Bitmap(bgm)


def httpadd(code,windows):
    appid="yktexshikvjg8lnq"
    appsecret="YlViYzFob3F2a055VjNMZjQxRHljQT09"
    url = "https://www.mxnzp.com/api/barcode/goods/details?app_id={}&app_secret={}&barcode={}".format(appid,appsecret,code)
    ret = requests.get(url)
    if ret.status_code == 200:
        ret = json.loads(ret.text)
        if ret['code'] == 0:
            wx.CallAfter(windows.LogMesrun,(0,"联网未查询到商品"))
        elif ret['code'] == 1:
            msg = "null,{},'{}','{}','{}',''".format(code,ret['data']['goodsName'],ret['data']['price'],ret['data']['standard'])
            ret = mysqldb.mysql.insert_data("inventory","ID,myid,name,price,ations,path",msg)
            if ret:
                wx.CallAfter(windows.LogMesrun,(1,code))
                wx.CallAfter(windows.LogMesrun,(0,"商品添加成功"))
    else:
        wx.CallAfter(windows.LogMesrun,(0,"联网添加失败,请重试,失败多次可联系开发者"))


def set_str(m,n):
    s = m.split("-")
    if n == len(s):
        return m
    elif len(s[n]) == 1:
        m = "-".join(["0" + i if s[n] == i else i for i in s])
    return set_str(m,n+1)


def ch_zh_sum(m,s=""):
    s += mydata.CH_ZH[m[0]][0]
    d = mydata.CH_ZH[str(len(m))][1]
    if m[0] != "0":
        s += d
    if d == "十":
        if m[-1] == "0":
            return s
        else:
            return s + mydata.CH_ZH[m[-1]][0]
    else:
        return ch_zh_sum(m[1:],s=s)


def ch_zh_han(m):
    if "." in str(m):
        m_str = str(m).split(".")
        try:
            m_str = m_str[0]+ "." + m_str[1][0] if int(m_str[1][1]) < 5 else str(int(m_str[1][0]) + 1)
        except:
            m_str = m_str[0]+ "." + m_str[1][0]
    else:
        m_str = str(m)
    h_str = str(int(m))
    if len(h_str) > 1:
        h_str = ch_zh_sum(h_str)
    else:
        h_str = mydata.CH_ZH[h_str][0]
    h_str = re.sub("零+","零",h_str)
    if h_str[-1] == "零":
        return h_str[:-1],m_str
    else:
        return h_str,m_str


def dict_update(dic,data,n):
    if n == "add":
        if data[0] in dic:
            su = dic[data[0]][1] + 1
            dic.update({data[0]:(data[1],su)})
        else:
            dic.update({data[0]:(data[1],1)})
    elif n == "del":
        su = dic[data[0]][1] - 1
        if su == 0:
            dic.pop(data[0])
        else:
            dic.update({data[0]:(dic[data[0]][0],su)})
    else:
        if data[0] in dic:
            su = dic[data[0]] + data[1]
            dic.update({data[0]:su})
        else:
            dic.update({data[0]:data[1]})


def erre_log(cor):
    with open("程序错误日志.log","a",encoding="utf-8") as log:
        st = time.strftime("%Y-%m-%d %H:%M:%S") + ": :" + cor + "\n"
        log.write(st)

